package com.yanqu.road.server.gameplayer.module.activity.tomb.dao;

import com.fasterxml.jackson.core.type.TypeReference;
import com.yanqu.road.dao.db.DbNameStrategy;
import com.yanqu.road.dao.db.DbParameter;
import com.yanqu.road.dao.dbV2.serializer.Helper;
import com.yanqu.road.dao.impl.TempDataObjectDao;
import com.yanqu.road.server.gameplayer.module.activity.tomb.entity.DbTombInfo;


import java.sql.*;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

public class UserTombInfoDaoImpl extends TempDataObjectDao<DbTombInfo> {


    public static UserTombInfoDaoImpl newInstance() {
        UserTombInfoDaoImpl dao = new UserTombInfoDaoImpl();
        return dao;
    }

    public static String updateSql = "update `t_u_activity_tomb_info` set activityId=?,partnerIdList=?,choseEventFinish=?,dollMap=?,score=?,unionScore=?,takeCareItemMap=?,updateTime=? where userId=? and activityId=?";

    @Override
    protected boolean updateData(DbTombInfo data) {
        data.setBeginWriteTime();
        getDb().setConnName(DbNameStrategy.getUserDb());
        int i = 1;
        Map<Integer, DbParameter> dbParameterMap = new HashMap<Integer, DbParameter>();
        dbParameterMap.put(i++, new DbParameter(Types.INTEGER, data.getActivityId()));
        dbParameterMap.put(i++, new DbParameter(Types.VARCHAR, Helper.toJSONString(data.getPartnerIdList())));
        dbParameterMap.put(i++, new DbParameter(Types.VARCHAR, Helper.toJSONString(data.getChoseEventFinish())));
        dbParameterMap.put(i++, new DbParameter(Types.VARCHAR, Helper.toJSONString(data.getDollMap())));
        dbParameterMap.put(i++, new DbParameter(Types.BIGINT, data.getScore()));
        dbParameterMap.put(i++, new DbParameter(Types.BIGINT, data.getUnionScore()));
        dbParameterMap.put(i++, new DbParameter(Types.VARCHAR, Helper.toJSONString(data.getTakeCareItemMap())));
        dbParameterMap.put(i++, new DbParameter(Types.BIGINT, data.getUpdateTime()));


        dbParameterMap.put(i++, new DbParameter(Types.BIGINT, data.getUserId()));
        if (data.isOldActivityIdZero()) {
            dbParameterMap.put(i++, new DbParameter(Types.INTEGER, 0));
            if (0 != data.getActivityId()) {
                data.setOldActivityIdZero(false);
            }
        } else {
            dbParameterMap.put(i++, new DbParameter(Types.INTEGER, data.getActivityId()));
        }



        if (getDb().executeNoneQuery(updateSql, dbParameterMap) > 0) {
            return true;
        }
        return false;
    }

    public static String insertSql = "insert into `t_u_activity_tomb_info`(userId,activityId,partnerIdList,choseEventFinish,dollMap,score,unionScore,takeCareItemMap,createTime,updateTime) values (?,?,?,?,?,?,?,?,?,?)";

    @Override
    protected boolean addData(DbTombInfo data) {
        data.setBeginWriteTime();
        getDb().setConnName(DbNameStrategy.getUserDb());
        int i = 1;
        Map<Integer, DbParameter> dbParameterMap = new HashMap<Integer, DbParameter>();
        dbParameterMap.put(i++, new DbParameter(Types.BIGINT, data.getUserId()));
        dbParameterMap.put(i++, new DbParameter(Types.INTEGER, data.getActivityId()));
        dbParameterMap.put(i++, new DbParameter(Types.VARCHAR, Helper.toJSONString(data.getPartnerIdList())));
        dbParameterMap.put(i++, new DbParameter(Types.VARCHAR, Helper.toJSONString(data.getChoseEventFinish())));
        dbParameterMap.put(i++, new DbParameter(Types.VARCHAR, Helper.toJSONString(data.getDollMap())));
        dbParameterMap.put(i++, new DbParameter(Types.BIGINT, data.getScore()));
        dbParameterMap.put(i++, new DbParameter(Types.BIGINT, data.getUnionScore()));
        dbParameterMap.put(i++, new DbParameter(Types.VARCHAR, Helper.toJSONString(data.getTakeCareItemMap())));
        dbParameterMap.put(i++, new DbParameter(Types.BIGINT, data.getCreateTime()));
        dbParameterMap.put(i++, new DbParameter(Types.BIGINT, data.getUpdateTime()));


        if (getDb().executeNoneQuery(insertSql, dbParameterMap) > 0) {
            return true;
        }
        return false;
    }


    @Override
    protected DbTombInfo parseData(ResultSet rs) throws SQLException {
        DbTombInfo data = DbTombInfo.newInstance();
        data.setUserId(rs.getLong("userId"));
        data.setActivityId(rs.getInt("activityId"));
        data.setPartnerIdList(Helper.toObject(rs.getString("partnerIdList"), new TypeReference<HashSet<Integer>>() {
        }));
        if (data.getPartnerIdList() == null) {
            data.setPartnerIdList(new HashSet<>());
        }
        data.setScore(rs.getLong("score"));
        data.setUnionScore(rs.getLong("unionScore"));
        data.setTakeCareItemMap(Helper.toObject(rs.getString("takeCareItemMap"), new TypeReference<ConcurrentHashMap<Integer, Long>>() {
        }));
        if (data.getTakeCareItemMap() == null) {
            data.setTakeCareItemMap(new ConcurrentHashMap<>());
        }
        data.setChoseEventFinish(Helper.toObject(rs.getString("choseEventFinish"), new TypeReference<HashSet<Integer>>() {
        }));
        if (data.getChoseEventFinish() == null) {
            data.setChoseEventFinish(new HashSet<>());
        }
        data.setDollMap(Helper.toObject(rs.getString("dollMap"), new TypeReference<ConcurrentHashMap<Integer, Long>>() {
        }));
        if (data.getDollMap() == null) {
            data.setDollMap(new ConcurrentHashMap<>());
        }

        data.setCreateTime(rs.getLong("createTime"));
        data.setUpdateTime(rs.getLong("updateTime"));

        return data;
    }

    public DbTombInfo getData(long userId) {
        ResultSet rs = null;
        CallableStatement call = null;
        String selectSql = "select * from t_u_activity_tomb_info where userId = ? order by createTime desc limit 1";
        try {
            getDb().setConnName(DbNameStrategy.getUserDb());
            call = getDb().getConnection().prepareCall(selectSql);
            call.setLong(1, userId);
            rs = call.executeQuery();
            if (rs.next()) {
                return parse(rs);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            getDb().closeConnection(call, rs);
        }
        return null;
    }

    public DbTombInfo getData(long userId, int activityId) {
        ResultSet rs = null;
        CallableStatement call = null;
        String selectSql = "select * from t_u_activity_tomb_info where userId = ? and activityId = ?";
        try {
            getDb().setConnName(DbNameStrategy.getUserDb());
            call = getDb().getConnection().prepareCall(selectSql);
            call.setLong(1, userId);
            call.setInt(2, activityId);
            rs = call.executeQuery();
            if (rs.next()) {
                return parse(rs);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            getDb().closeConnection(call, rs);
        }
        return null;
    }


    public Map<Integer, DbTombInfo> getDataMap(long userId) {
        ResultSet rs = null;
        CallableStatement call = null;
        Map<Integer, DbTombInfo> dataMap = new ConcurrentHashMap<>();
        String selectSql = "select * from t_u_activity_tomb_info where userId = ?";
        try {
            getDb().setConnName(DbNameStrategy.getUserDb());
            call = getDb().getConnection().prepareCall(selectSql);
            call.setLong(1, userId);
            rs = call.executeQuery();
            while (rs.next()) {
                DbTombInfo data = parse(rs);
                dataMap.put(data.getActivityId(), data);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            getDb().closeConnection(call, rs);
        }
        return dataMap;
    }

    public boolean saveData(DbTombInfo data) {
        if (data.isUpdateOption()) {
            if (data.isNeedInsert()) {
                if (addData(data)) {
                    data.setNeedInsert(false);
                }
            } else {
                data.setUpdateTime(System.currentTimeMillis());
                update(data);
            }
        }
        return true;
    }

}
